import { getRoleList } from './service';

const Model = {
  namespace: 'smRoleRule',
  state: {
    roleListData: {},
    ruleData: [],
    tableRef: {},
  },
  effects: {
    *getRoleList({ payload, resolve }, { call, put }) {
      const params = {
        ...payload,
        pageNum: payload.current,
        pageSize: payload.pageSize,
      };
      const response = yield call(getRoleList, params);

      if (!response.error) {
        const { records, page, totalNum } = response;
        const result = {
          data: records,
          page,
          pageSize: payload.pageSize,
          success: true,
          total: totalNum,
        };
        for (let i = 0; i < response.records.length; i++) {
          const arr = [];
          let arrs = '';
          for (let j = 0; j < response.records[i].permissions.length; j++) {
            arr.push(response.records[i].permissions[j].name);
          }
          arrs = arr.join('，');
          response.records[i].permissions = arrs;
        }
        resolve && resolve(result);

        yield put({
          type: 'save',
          payload: {
            roleListData: result,
          },
        });
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
    tableReload(state) {
      const tableRef = state.tableRef || {};
      setTimeout(() => {
        tableRef.current.reloadAndRest();
      }, 0);
      return { ...state };
    },
  },
};
export default Model;
